package com.aqie.meet.ui.my;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.aqie.libbase.event.EventManager;
import com.aqie.libbase.event.MessageEvent;
import com.aqie.libcommon.adapter.CommonAdapter;
import com.aqie.libcommon.adapter.CommonViewHolder;
import com.aqie.libcommon.app.BaseApplication;
import com.aqie.libcommon.utils.CommonUtils;
import com.aqie.libcommon.utils.SimpleJsonTool;
import com.aqie.libcommon.view.EmptyView;
import com.aqie.libfactory.data.helper.DbHelper;
import com.aqie.libfactory.data.helper.UserHelper;
import com.aqie.libfactory.model.api.PageList;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.file.FileModel;
import com.aqie.libfactory.model.api.user.UserPost;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libnavanotation.FragmentDestination;
import com.aqie.meet.R;
import com.aqie.meet.databinding.MyFragmentBinding;
import com.aqie.meet.helper.FileHelper;
import com.aqie.meet.manager.DialogManager;
import com.aqie.meet.ui.BusinessBaseFragment;
import com.aqie.meet.ui.find.PostDetailActivity;
import com.aqie.meet.ui.location.LocationActivity;
import com.aqie.meet.ui.login.AccountActivity;
import com.aqie.meet.utils.TimeUtils;
import com.aqie.meet.utils.Utils;
import com.aqie.meet.view.AImageView;
import com.aqie.meet.view.DialogView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import circletextimage.viviant.com.circletextimagelib.view.CircleTextImage;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;
import static com.aqie.meet.helper.FileHelper.ALBUM_REQUEST_CODE;

@FragmentDestination(pageUrl = "main/tabs/my", asStarter = false,needLogin = true)
public class MyFragment extends BusinessBaseFragment {
    private MyFragmentBinding mBinding;
    protected Unbinder mRootUnBinder;

    MyViewModel mViewModel;

    @BindView(R.id.my_set)
    TextView mSet;
    @BindView(R.id.my_resource_set)
    TextView mResourceSet;

    @BindView(R.id.recycler_view)
    RecyclerView mRecycleView;

    @BindView(R.id.empty_view)
    EmptyView mEmptyView;

    @BindView(R.id.tag_avatar)
    CircleTextImage mCircleTextImage;

    // 用户信息编辑
    @BindView(R.id.tag_username)
    EditText username;
    @BindView(R.id.tag_trade2)
    EditText trade;
    @BindView(R.id.tag_position2)
    EditText position;
    @BindView(R.id.tag_city)
    EditText city;
    @BindView(R.id.tag_years)
    EditText years;
    @BindView(R.id.et_answer_one)
    EditText one;
    @BindView(R.id.et_answer_two)
    EditText two;
    @BindView(R.id.et_answer_three)
    EditText three;

    @BindView(R.id.btn_submit)
    TextView submit;
    @BindView(R.id.btn_cancel)
    TextView cancel;

    // 点击上传头像
    CircleTextImage mAvatar;
    @BindView(R.id.tag_avatar_true)
    AImageView mTrueAvatar;

    //头像文件
    private File uploadPhotoFile;
    private String uploadFilePath = "";

    //头像选择框
    private DialogView mPhotoDialog;
    // TextView tv_camera;
    TextView tv_ablum;
    TextView tv_photo_cancel;

    @SuppressLint("ResourceAsColor")
    private void setEnable(boolean is){
        username.setEnabled(is);
        trade.setEnabled(is);
        position.setEnabled(is);
        city.setEnabled(is);
        years.setEnabled(is);
        one.setEnabled(is);
        two.setEnabled(is);
        three.setEnabled(is);
        username.setActivated(is);
        cancel.setVisibility(is ? View.VISIBLE : View.GONE);
        if(is){
            city.requestFocus();
            //username.setSelection(username.getText().length());
            /*one.requestFocus();
            one.setFocusable(true);
            one.setFocusableInTouchMode(true);
            one.setSelection(one.getText().length());*/
            /*username.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (MotionEvent.ACTION_DOWN == event.getAction()) {
                        username.setCursorVisible(true);
                    }
                    return false;
                }
            });
            username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {

                    if (hasFocus) {
                        // 这里是关键代码了
                        username.setTextIsSelectable(true);
                    }
                }
            });


            username.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    username.setCursorVisible(true);
                    username.setFocusable(true);
                    username.setFocusableInTouchMode(true);
                    username.requestFocus();
                    username.setSelection(username.getText().length());
                    // BaseApplication.showToast("click");
                }
            });*/

        }else {
            username.clearFocus();
        }
        int i = is ? View.VISIBLE : View.GONE;
        submit.setVisibility(i);
    }

    private List<UserPost> mList = new ArrayList<>();
    private CommonAdapter<UserPost> mAdapter;

    private User data;

    @Nullable
    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = MyFragmentBinding.inflate(inflater, container, false);
        mRootUnBinder = ButterKnife.bind(this, mBinding.getRoot());
        initView(mBinding.getRoot());
        initPhotoDialog();
        EventManager.register(this);
        return mBinding.getRoot();
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getMyBase();

    }

    @Override
    public void onResume() {
        super.onResume();
        getMyPost();
    }

    private void initView(View view) {
        // 选择显示头像

        mAvatar = view.findViewById(R.id.tag_avatar);
        // 个人资料初始禁止编辑
        setEnable(false);
        mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        // Log.e(TAG, "list:" + mList.toString());

        mAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<UserPost>() {
            @Override
            public void onBindViewHolder(UserPost model, CommonViewHolder viewHolder, int type, int position) {
                fillData(model, viewHolder);
                // 动态点赞
                digOrUndig(model, viewHolder);

                // 跳转详情
                viewHolder.getView(R.id.posts).setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                    intent.putExtra("postId", model.getId());
                    startActivity(intent);
                });
                viewHolder.getView(R.id.comment_num).setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), PostDetailActivity.class);
                    intent.putExtra("postId", model.getId());
                    startActivity(intent);
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.my_posts_item;
            }
        });
        mRecycleView.setAdapter(mAdapter);


        //监听列表滑动
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }



    private void fillData(UserPost model, CommonViewHolder viewHolder) {
        viewHolder.setText(R.id.post_text, model.getContent());
        if(model.getPictureList() != null && !model.getPictureList().isEmpty()){
            viewHolder.setImageUrl(getActivity(), R.id.post_images, model.getPictureList().get(0));
        }else {
            viewHolder.goneIfEmpty(R.id.post_images);
        }
        viewHolder.setText(R.id.post_time, TimeUtils.calculate(model.getPublishTime()));
        // 开始喜欢
        if(model.getBoolLike()){
            viewHolder.setText(R.id.liked_num, String.valueOf(model.getLikeCount()));
            viewHolder.goneIfEmpty(R.id.like_num);
            viewHolder.show(R.id.liked_num);
        } else {
            viewHolder.setText(R.id.like_num, String.valueOf(model.getLikeCount()));
            viewHolder.goneIfEmpty(R.id.liked_num);
            viewHolder.show(R.id.like_num);
        }


        viewHolder.setText(R.id.comment_num, String.valueOf(model.getCommentCount()));
    }

    /**
     * 获取我的动态
     */
    private void getMyPost() {
        RemoteService service = Network.remote();
        Call<RspModel<PageList<UserPost>>> call = service.minePost(1, 1000);
        call.enqueue(new Callback<RspModel<PageList<UserPost>>>() {
            @Override
            public void onResponse(Call<RspModel<PageList<UserPost>>> call, Response<RspModel<PageList<UserPost>>> response) {
                RspModel<PageList<UserPost>> body = response.body();
                if(body !=null && body.success()){
                    PageList<UserPost> posts = body.getData();
                    String rspString = SimpleJsonTool.toJson(posts); Log.e(TAG, rspString);
                    if(posts.getTotal() == 0) {
                        mRecycleView.setVisibility(View.GONE);
                        mEmptyView.setVisibility(View.VISIBLE);
                    } else {
                        mRecycleView.setVisibility(View.VISIBLE);
                        mEmptyView.setVisibility(View.GONE);
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                        mList.addAll(posts.getRecords());
                        mAdapter.notifyDataSetChanged();
                        // Log.e(TAG, "my list:" + mList.toString());
                    }
                }else {
                    Log.e(TAG, "request fail: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<RspModel<PageList<UserPost>>> call, Throwable t) {
                Log.e(TAG, "request fail: onFailure");
            }
        });
    }

    /**
     * 获取我的个人信息
     */
    private void getMyBase() {
        RemoteService service = Network.remote();
        Call<RspModel<User>> call = service.mineBase();
        call.enqueue(new Callback<RspModel<User>>() {
            @Override
            public void onResponse(Call<RspModel<User>> call, Response<RspModel<User>> response) {

                RspModel<User> body = response.body();
                if(response.code() == 401){
                    // 跳转登录界面
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    data = body.getData();
                    uploadFilePath = data.getAvatar();
                    // String rspString = SimpleJsonTool.toJson(data); Log.e(TAG, rspString);
                    mBinding.setUserInfo(data);
                    // 用户头像不为空显示网络头像
                    if(data.getAvatar() != null){
                        mTrueAvatar.setVisibility(View.VISIBLE);
                        mTrueAvatar.setImageUrl(data.getAvatar());
                        mAvatar.setVisibility(View.GONE);
                    } else {
                        // 用户名不为空展示文字头像
                        if(data != null && data.getUsername() != null && data.getUsername().length() > 0) {
                            mCircleTextImage.setText4CircleImage(Utils.getName(data.getUsername()));
                        }
                    }
                    // 保存用户信息到数据库
                    DbHelper.save(User.class, data);
                    User search = UserHelper.search(data.getUserId());
                    Log.e(TAG, search.toString());

                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<User>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
        // TODO: Use the ViewModel
    }



    // 个人资料编辑
    @OnClick(R.id.my_resource_set)
    void clickMaterialSetting(){
        if(data == null){
            AccountActivity.show(getActivity());
            return;
        }

        mResourceSet.setVisibility(View.GONE);
        cancel.setVisibility(View.VISIBLE);
        setEnable(true);
    }

    @OnClick(R.id.btn_cancel)
    void cancelEdit(){
        mResourceSet.setVisibility(View.VISIBLE);
        setEnable(false);
        cancel.setVisibility(View.GONE);
        getMyBase();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (!CommonUtils.isEmpty(mList)) {
                // BaseApplication.showToast("获取我的发布");
                getMyPost();
            }
        }
    }

    @OnClick(R.id.btn_submit)
    void submit(){
        User model = new User();
        model.setAvatar(uploadFilePath);
        model.setUsername(username.getText().toString());
        model.setTrade(trade.getText().toString());
        model.setPosition(position.getText().toString());
        model.setCity(city.getText().toString());
        try{
            model.setWorkingYears(Integer.valueOf(years.getText().toString()));
        }catch (Exception e) {
            model.setWorkingYears(1);
        }

        model.setAnswerOne(one.getText().toString());
        model.setAnswerThree(three.getText().toString());
        model.setAnswerTwo(two.getText().toString());
        modifyUserInfo(model);
        mBinding.setUserInfo(model);
    }

    /**
     * 修改个人信息
     * @param model
     */
    protected void modifyUserInfo(User model){
        RemoteService service = Network.remote();
        Call<RspModel<Boolean>> call = service.mineUpdate(model);
        call.enqueue(new Callback<RspModel<Boolean>>() {
            @Override
            public void onResponse(Call<RspModel<Boolean>> call, Response<RspModel<Boolean>> response) {

                RspModel<Boolean> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getActivity());
                    return;
                }
                if(body !=null && body.success()){
                    setEnable(false);
                    mResourceSet.setVisibility(View.VISIBLE);
                    cancel.setVisibility(View.GONE);
                    BaseApplication.showToast("更新用户信息成功");
                }else {
                    Log.e(TAG, "request fail");
                }
            }

            @Override
            public void onFailure(Call<RspModel<Boolean>> call, Throwable t) {
                Log.e(TAG, t.getMessage());
            }
        });
    }

    @OnClick(R.id.tag_avatar)
    void uploadAvatar(){
        DialogManager.getInstance().show(mPhotoDialog);
    }

    @OnClick(R.id.tag_avatar_true)
    void uploadAvatarTrue(){
        DialogManager.getInstance().show(mPhotoDialog);
    }

    /**
     * 头像选择
     */
    private void initPhotoDialog() {
        mPhotoDialog = DialogManager.getInstance().initView(getActivity(),
                R.layout.dialog_select_photo, Gravity.BOTTOM);

        //tv_camera = (TextView) mPhotoDialog.findViewById(R.id.tv_camera);
        tv_ablum = (TextView) mPhotoDialog.findViewById(R.id.tv_ablum);
        tv_photo_cancel = (TextView) mPhotoDialog.findViewById(R.id.tv_cancel);

        /*tv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mPhotoDialog);
                FileHelper.getInstance().toCamera(getActivity());
            }
        });*/
        tv_ablum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mPhotoDialog);
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, ALBUM_REQUEST_CODE);
                // FileHelper.getInstance().toAlbum(getActivity());
            }
        });
        tv_photo_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mPhotoDialog);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);   //this
        if (resultCode == RESULT_OK) {
            if (requestCode == FileHelper.CAMEAR_REQUEST_CODE) {
                FileHelper.getInstance().startPhotoZoom(getActivity(), FileHelper.getInstance().getTempFile());
            } else if (requestCode == ALBUM_REQUEST_CODE) {
                Uri uri = data.getData();
                if (uri != null) {
                    String path = FileHelper.getInstance().getRealPathFromURI(getActivity(), uri);
                    if (!TextUtils.isEmpty(path)) {
                        uploadPhotoFile = new File(path);
                        FileHelper.getInstance().startPhotoZoom(getActivity(), uploadPhotoFile);
                    }
                }
            } else if (requestCode == FileHelper.CAMERA_CROP_RESULT) {
                uploadPhotoFile = new File(FileHelper.getInstance().getCropPath());
                Log.e(TAG, "uploadPhotoFile:" + uploadPhotoFile.getPath());
            }
            // 本地头像上传成功 隐藏文字头像
            if (uploadPhotoFile != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(uploadPhotoFile.getPath());
                mTrueAvatar.setVisibility(View.VISIBLE);
                mTrueAvatar.setImageUrl(uploadPhotoFile.getPath());
                // mTrueAvatar.setImageBitmap(bitmap);
                mAvatar.setVisibility(View.GONE);
                // 上传头像到服务器
                uploadImgToNet();
            }
        }
    }

    // 单个文件上传
    protected void uploadImgToNet() {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadPhotoFile);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", uploadPhotoFile.getName(), requestFile);
        RemoteService service = Network.remote();
        Call<RspModel<FileModel>> call = service.upload(filePart);
        call.enqueue(new Callback<RspModel<FileModel>>() {
            @Override
            public void onResponse(Call<RspModel<FileModel>> call, Response<RspModel<FileModel>> response) {
                RspModel<FileModel> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getActivity());
                    return;
                }
                if(body !=null && body.success()){
                    BaseApplication.showToast("上传成功");
                    // Log.e(TAG, body.getData().toString());
                    uploadFilePath = body.getData().getPath();
                    // Log.e(TAG, uploadFilePath);
                    // 更新用户信息
                    User model = new User();
                    model.setAvatar(uploadFilePath);
                    modifyUserInfo(model);
                }
            }

            @Override
            public void onFailure(Call<RspModel<FileModel>> call, Throwable t) {

            }
        });
    }

    @OnClick(R.id.my_set)
    void clickMySet(){
        LocationActivity.show(getActivity());
        /*if(data == null){
            AccountActivity.show(getActivity());
            return;
        }
        Intent intent = new Intent(getActivity(), MySettingActivity.class);
        intent.putExtra("boolChat", data.getBoolChat());
        startActivity(intent);*/
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent<Integer> event) {
        switch (event.getType()) {
            case EventManager.EVENT_REFRE_ME_INFO:
                Integer d = event.getData();
                // Log.e(TAG, "接收到更新消息" + d);
                data.setBoolChat(d);
                break;
        }
    }

}